;;; clojure.cfg.el --- Summary
;;; Commentary:
;;; clojure configuration
;;; Code:
(defconst my-kibit-version-regexp "\\[lein-kibit.*\"\\([0-9\.]+\\)\"\\]")
(defconst my-kibit-version "0.1.2")
(defconst my-lein-profiles-file (expand-file-name "~/.lein/profiles.clj"))

(defun my-update-versions (regexp current-version &optional custom-message-format)
  "Search for REGEXP and update to CURRENT-VERSION in current buffer logging CUSTOM-MESSAGE-FORMAT."
  (progn
    (goto-char (point-min))
    (while (re-search-forward regexp nil t)
      (unless (string= current-version (match-string 1))
        (replace-match
         current-version nil nil nil 1))))
  (when (buffer-modified-p (current-buffer))
    (message (format (or custom-message-format "Version updated to %s")
                     current-version))))

(defun my-update-lein-profiles-cider-nrepl ()
  "Update versions in ~/.lein/profiles.clj.
If the dependency is not specified, nothing will happen."
  (save-excursion
    (let* ((already-open
            (car (cl-remove-if-not
                  (lambda (x) (string= my-lein-profiles-file
                                       (buffer-file-name x)))
                  (buffer-list))))
           (lein-profiles-buffer (or already-open
                                     (find-file-noselect my-lein-profiles-file))))
      (with-current-buffer lein-profiles-buffer
        (my-update-versions my-kibit-version-regexp my-kibit-version "kibit version updated to %s")
        (when (buffer-modified-p lein-profiles-buffer)
          (save-buffer))
        (unless already-open
          (kill-buffer lein-profiles-buffer))))))

(use-package clojure-mode
  :functions cider-doc
  :defines cider-repl-display-help-banner
  :init
  (add-hook 'clojure-mode-hook #'my-update-lein-profiles-cider-nrepl)
  (add-hook 'clojure-mode-hook #'subword-mode)
  (add-hook 'clojure-mode-hook #'smartparens-strict-mode)
  :config
  (setq cider-repl-display-help-banner nil)
  (use-package kibit-helper
    :functions cider-doc
    :init
    ;; kibit is a static analyzer that suggests idiomatic clojure code
    :bind (:map clojure-mode-map
                ("C-c k a" . kibit-accept-proposed-change)
                ("C-c k p" . kibit)
                ("C-c k f" . kibit-current-file))))

(use-package cider
  :functions cider-doc
  :init
  (add-hook 'cider-mode-hook #'eldoc-mode)
  (add-hook 'cider-repl-mode-hook #'subword-mode)
  (add-hook 'cider-repl-mode-hook #'smartparens-strict-mode)
  :bind (:map cider-mode-map
              ("M-?" . cider-doc)
              :map cider-repl-mode-map
              ("M-?" . cider-doc))
  :config
  (setq cider-repl-tab-command 'indent-for-tab-command
        cider-prefer-local-resources t
        cider-repl-use-pretty-printing t
        cider-repl-result-prefix ";; => "))

(provide 'clojure.cfg)
;;; clojure.cfg.el ends here
